package com.sinosun.autotestmachine.tools.Excutor;

import org.json.JSONArray;
import org.json.JSONException;

import com.sinosun.autotestmachine.App;
import com.sinosun.autotestmachine.tools.TaskManager;
import com.sinosun.autotestmachine.tools.Collector.Cache;
import com.sinosun.autotestmachine.tools.parser.CaseInformation;
import com.sinosun.autotestmachine.tools.parser.ContentMaker;
import com.sinosun.autotestmachine.tools.parser.StepParser;
import com.sinosun.autotestmachine.tools.proxy.ErrorCode;
import com.sinosun.autotestmachine.tools.proxy.ProxyWrapper;

import android.text.TextUtils;
import android.util.Log;

public class CaseScheduler {
	private static final String STEP = "step";
	private static CaseScheduler instance = null;
	private CaseScheduler () { }
	
	public static CaseScheduler getInstance() {
		if (instance == null) {
			instance = new CaseScheduler();
		}
		return instance;
	}
	
	/**
	 * 执行任务
	 * @param caseInfo
	 */
	public void runCaseTask(CaseInformation caseInfo) {
		if (caseInfo == null) return;
		try {
			JSONArray stepJsonArray = new JSONArray(caseInfo.getCaseContent());
			int stepNum = stepJsonArray.length();
			if (stepNum == 0) return;
			Class clazz = App.getInstance().getApplicationContext().getClassLoader().loadClass(ProxyWrapper.class.getName());
			Object obj = clazz.newInstance();
			
			Log.e("XXX", "===> case " + caseInfo.getCaseDecription() + " start with " + stepNum + " steps");
			for (int i = 0; i < stepNum; i++) {
				if (!TextUtils.isEmpty(stepJsonArray.getString(i))) {
					if (stepJsonArray.getJSONObject(i).has(STEP)) {
						int tagFlag = StepParser.getStepParser().parser(caseInfo.getCaseId(), clazz, obj, stepJsonArray.getJSONObject(i).getString(STEP), caseInfo.getTaskID());	//步骤运行出错，直接添加 )
						if (tagFlag != ErrorCode.SUCCESS) {
							break;
						}
					}
				}
			}
			Cache.clearCache();
			ContentMaker.delAllFile(App.getInstance().getUploadPath());
			ContentMaker.delAllFile(App.getInstance().getDownloadPath());
			TaskManager.getTaskManager().startWaitToEnd(); 			//保证 case 运行结束后归为同步
			Log.e("XXX", "===>case " + caseInfo.getCaseDecription() + "end <===");
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
